﻿$(document).ready(Page_Load);

var rowdata;
var roledata;
var currentId;

function Page_Load(e) {
    LoadGrid();

    var int = self.setInterval("GetUsers()", 300000);

    GetRoles();
}
    
    function GetUsers(){
         
        $.ajax(
            {
                type: "POST",
                async: true,
                url: "Users.aspx/GetAllUsers",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: LoadUserStats_Success,
                error: LoadUserStats_Error
            });
    
    }


    function LoadUserStats_Success(data, textStatus, XMLHttpRequest) {
        rowdata = data.d;
        BindGrid( $("#list2"), rowdata, "UserId", 1);
    }

    function LoadUserStats_Error(XMLHttpRequest, textStatus, errorThrown) {
        Log(XMLHttpRequest, "LoadUserStats", 100);
        alert("An error occurred loading the user statistics. Error: " + XMLHttpRequest);

    }

    function LoadGrid() {

        $("#list2").jqGrid(
        {
            datatype: "local",
            colNames: ['', 'Id', 'Name', 'Email', '<img src=/Images/Key.png height=16 alt=\"Approved?\" title=\"Approved?\">', '<img src=/Images/2608_GoldLock_48x48.png height=16 alt=\"LockedOut?\" title=\"LockedOut?\">', '<img src=/Images/mynet.png height=16 alt=\"Online?\" title=\"Online?\">', 'Created', 'Last Activity', ''],
            colModel: [
                { name: 'act', index: 'act', width: 125, sortable: false, align: 'center' },
                { name: 'id', index: 'id', width: 55, search: false, hidden: true, editable: false },
   		        { name: 'UserName', index: 'UserName', width: 150, editable: false },
   		        { name: 'Email', index: 'Email', width: 150, edittype: "text", editable: true },
                { name: 'IsApproved', index: 'IsApproved', width: 25, align: 'center', formatter: CheckBoxFormatter, edittype: "checkbox", editable: true },
                { name: 'IsLockedOut', index: 'IsLockedOut', width: 25, align: 'center', formatter: CheckBoxFormatter, edittype: "checkbox", editable: true },
                { name: 'IsOnline', index: 'IsOnline', width: 25, align: 'center', formatter: CheckBoxFormatter, editable: false },
                { name: 'CreationDate', index: 'CreationDate', width: 125, editable: false },
                { name: 'LastActivityDate', index: 'LastActivityDate', width: 125, editable: false },
                { name: 'act2', index: 'act2', width: 38, sortable: false }
            ],
            rowNum: 10,
            rowList: [10, 20, 30],
            pager: '#pager2',
            sortname: 'UserName',
            viewrecords: true,
            sortorder: "desc",
            caption: "Users",
            height: 250,
            width: "100%",      
            editurl: 'somepage.aspx',
            gridComplete: function () {
                var ids = $("#list2").jqGrid('getDataIDs');
                for (var i = 0; i < ids.length; i++) {
                    var cl = ids[i];
                    lock = "<img class=\'gridaction\' src=\'/Images/Encrypt.png\' alt=\'Lock or Unlock\' title=\'Lock or Unlock\' onclick=\"UnlockUser('" + cl + "');\"/>";
                    activate = "<img class=\'gridaction\' src=\'/Images/base_checkmark_32.png\' alt=\'Activate\' title=\'Activate\' onclick=\"ApproveUser('" + cl + "');\"/>";
                    ed = "<img class=\'gridaction\' src=\'/Images/Page.png\' alt=\'Edit\' title=\'Edit\' onclick=\"EditUser('" + cl + "');\"/>";
                    de = "<img class=\'gridaction\' src=\'/Images/delete.png\' height=32 width=32 alt=\'Delete\' title=\'Delete\' onclick=\"DeleteUser('" + cl + "');\"/>";
                    addrole = "<img class=\'gridaction\' src=\'/Images/Users.png\' height=32 width=32 alt=\'Add User To Role\' title=\'Add User To Role\' onclick=\"AddUserToRole('" + cl + "');\"/>"; 
                    $("#list2").jqGrid('setRowData', ids[i], { act: lock + activate + ed, act2: de });
                }
            }
        });

        $("#list2").jqGrid('navGrid', '#pager2', { edit: false, add: false, del: false, beforeRefresh: function () { GetUsers(); } })


        GetUsers();
    }


    function CheckBoxFormatter(cellvalue, options, rowObject) {
        switch (cellvalue) {
            case "true":
                return "<input type=checkbox disabled checked title=Yes>";
                break;
            default:
                return "<input type=checkbox disabled title=No>";
                break;
        }
    }  




function UnlockUser(user) {
    var userdata = $("#list2").jqGrid('getRowData', user);

    if (userdata["UserName"] != "Administrator") {
        var webMethodParams = JSON.stringify({ UserId: user });

        $.ajax(
            {
                type: "POST",
                async: true,
                url: "Users.aspx/UnlockUser",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: RefreshGrid,
                error: Command_Error
            });
        }
        else {
            DisplayAdminLockdownMessage();
        }
}

function ApproveUser(user) {
    var userdata = $("#list2").jqGrid('getRowData', user);

    if (userdata["UserName"] != "Administrator") {
        var webMethodParams = JSON.stringify({ UserId: user });
        $.ajax(
            {
                type: "POST",
                async: true,
                url: "Users.aspx/ApproveUser",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: RefreshGrid,
                error: Command_Error
            });
        }
        else {
            DisplayAdminLockdownMessage();
        }
}

function EditUser(user) {
    var userdata = $("#list2").jqGrid('getRowData', user);

    $("#name").html(userdata["UserName"]);

    $("#dialog-updateuser").dialog({
        resizable: false,
        height: 265,
        width: 425,
        modal: true,
        buttons: {
            'Update': function () {
                ValidateUserUpdate(user);
               
            },
            'Cancel': function () {
                $(this).dialog('close');
            }
        },
        close: function () {
            $("#email").val("");

            $("#error-container").removeClass("ui-state-error ui-corner-all");
            $("#error").html("");

            $('input').removeClass("ui-state-error");
        }
    });
}

function ValidateUserUpdate(user) {
    var	email = $("#email");

    var bValid = true;

    bValid = bValid && checkLength(email, "email", 6);
    
    bValid = bValid && checkRegexp(email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "Enter a valid email address.  eg. user@email.com");


    if (bValid) {
        $(this).dialog('close');
        UpdateUser(user);
    }
}

function UpdateUser(user) {
    var email = $("#email").val();

    var webMethodParams = JSON.stringify({ UserId: user, Email: email });
    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Users.aspx/UpdateUser",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: RefreshGrid,
                error: Command_Error
            });
}


function RefreshGrid(data, textStatus, XMLHttpRequest) {
    GetUsers();
}

function Command_Error(XMLHttpRequest, textStatus, errorThrown) {
    Log(XMLHttpRequest, "LoadUserStats", 100);
    alert("An error occurred loading the user statistics. Error: " + XMLHttpRequest);

}

function DeleteUser(user) {
    var userdata = $("#list2").jqGrid('getRowData', user);

    if (userdata["UserName"] != "Administrator") {
        var $dialog = $('<div></div>')
		.html('Please confirm the delete request (' + userdata["UserName"] + ').')
		.dialog({
		    autoOpen: false,
		    resizable: false,
		    height: 200,
		    width: 400,
		    modal: true,
		    buttons: {
		        'Yes': function () {
		            DeleteConfirmed(user);
		            $(this).dialog('close');
		        },
		        'No': function () {
		            $(this).dialog('close');
		        }
		    },
		    title: 'Confirm Delete'
		});
        $dialog.dialog('open');
    }
    else {
        DisplayAdminLockdownMessage();
    }
}


function DeleteConfirmed(user) {
    var webMethodParams = JSON.stringify({ UserId: user });
    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Users.aspx/DeleteUser",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: RefreshGrid,
                error: Command_Error
            });
}


function DisplayAdminLockdownMessage() {
    var $dialog = $('<div></div>')
		.html('Unable to modify the default administrator account.')
		.dialog({
		    autoOpen: false,
		    resizable: false,
		    height: 200,
		    width: 400,
		    modal: true,
		    title: 'Error'
		});
    $dialog.dialog('open');

}

